<template>
	<view class="content">
		<view class="tips">
			你好，欢迎回家！
		</view>
		<u-swiper :list="list" mode="number" duration="1500" style="width:100%"></u-swiper>
		<view class="operation-bar">
			<!-- <view class="operation-item">
				<u-badge type="error" count="7" :is-dot="true" :offset="[0, 0]"></u-badge>
				<view class="icon-box">
					<u-icon name="photo"></u-icon>
				</view>
				<view class="operation-text">
					合同
				</view>
			</view> -->
			<view class="operation-item" @click="goBill">
				<u-badge type="error" :count="overdueCount" :offset="[0, 0]"></u-badge>
				<view class="icon-box">
					<u-icon name="order"></u-icon>
				</view>
				<view class="operation-text">
					账单
				</view>
			</view>
			<!-- <view class="operation-item" @click="() => this.$tab.navigateTo('/pages/home/repair/index')">
				<u-badge type="error" count="7" :is-dot="true" :offset="[0, 0]"></u-badge>
				<view class="icon-box">
					<u-icon name="photo"></u-icon>
				</view>
				<view class="operation-text">
					报修
				</view>
			</view> -->
			<view class="operation-item" @click="goToRooms">
				<u-badge type="error" class="text-badge" :count="0" :offset="[0, 0]"></u-badge>
				<view class="icon-box">
					<u-icon name="home"></u-icon>
				</view>
				<view class="operation-text">
					房间
				</view>
			</view>
		</view>
		<view class="notice-bar">
			<u-notice-bar
				:list="noticeList" 
				mode="vertical"
				:more-icon="true"
				:speed="80"
				:duration="3000"
				padding="8rpx 16rpx"
				:no-list-hidden="true"
				@click="showNoticeDetail"
			></u-notice-bar>
		</view>
		<view class="lock-section">
			<view class="lock-bar" v-if="lockList.length > 0">
				<view 
					class="lock-item" 
					v-for="(item, index) in lockList" 
					:key="index" 
					@click="toClickItem(item)"
					:class="{'lock-item-disabled': hasOverdueBill && (item.deviceType === 1 || item.deviceType === 3)}"
				>
					<tai-card>
						<view style="height: 224rpx;">
							<view class="flex-row">
								<view style="height: 120rpx;width: 80rpx;">
									<img v-if="item.deviceType === 1 || item.deviceType === 3" src="../static/images/electricity_lock.png" alt="" style="width: 100%;height: 100%;object-fit: cover;" />
									<img v-if="item.deviceType === 2" src="../static/images/electricity_meter.png" alt="" style="width: 100%;height: 80%;object-fit: cover;" />
								</view>
								<TaiLock size="100rpx" v-if="item.deviceType === 1 || item.deviceType === 3">
									<view 
										style="font-size: 20rpx;" 
										:style="{color: hasOverdueBill ? '#999' : 'dodgerblue'}" 
										@click="unLock(item)"
									>
										开锁
										<view v-if="hasOverdueBill" class="overdue-badge">已逾期</view>
									</view>
								</TaiLock>	
							</view>
							<view style="margin: 16rpx 0;">
								{{	item.deviceName || '-'}}
							</view>
							<view class="flex-row" v-if="item.deviceType === 1">
								<BatteryIcon :number="item.lockInfo.electricQuantity"></BatteryIcon>
								<view v-if="item.deviceType === 1" class="pre-dot" :class="{'disabled-text': hasOverdueBill}">
									去设置
								</view>
							</view>
							<view class="flex-row" v-if="item.deviceType === 2">
								<view :style="{fontSize: '24rpx'}">
									状态：<span :style="{color: item.online == '0' ? 'green' : 'red'}">{{item.online == "0" ? "在线" : "离线"}}</span>
								</view>
								<view class="pre-dot" @click="toRecharge(item)">
									去充值
								</view>
							</view>
						</view>
					</tai-card>
				</view>
				<!-- <button type="default" @click="unBindWechat">解绑微信</button> -->
			</view>
			<view class="empty-lock" v-else>
				暂无电子钥匙，请联系管家
			</view>
		</view>
		<u-modal v-model="showModal" :title="modalTitle" 
			:content="modalContent" :show-cancel-button="true" 
			:confirm-text="currentAlert.type === 3 ? '去充值' : '去缴费'" @cancel="closeModal" @confirm="goToPay">
			<view slot="default" class="modal-content">
				<view class="modal-item">
					<text class="modal-label">房间名称：</text>
					<text class="modal-value">{{ currentAlert.roomName || '-' }}</text>
				</view>
				<view class="modal-item">
					<text class="modal-label">预警类型：</text>
					<text class="modal-value">{{ getAlertTypeName(currentAlert.type) }}</text>
				</view>
				<view class="modal-item">
					<text class="modal-label">{{ currentAlert.type === 3 ? '余额' : '金额' }}：</text>
					<text class="modal-value">{{ currentAlert.money || 0 }}元</text>
				</view>
				<view class="modal-item" v-if="currentAlert.type === 1 || currentAlert.type === 2">
					<text class="modal-label">应缴日期：</text>
					<text class="modal-value">{{ currentAlert.noticeDate || '-' }}</text>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import TaiCard from '@/components/tai-card/index'
	import TaiLock from '@/components/tai-lock/index.vue'
	import BatteryIcon from '@/components/battery-icon/index.vue'
import { associatedDevice, faceLockUnLock } from '@/api/device/lock'
import { lowBalanceMeters } from '@/api/device/index'
import { roomList } from '@/api/room'
import banner01 from '@/static/images/banner/banner01.jpg'
import banner02 from '@/static/images/banner/banner02.jpg'
import banner03 from '@/static/images/banner/banner03.jpg'
import { unbindWechat } from '../api/login'
// import { uBadge, uIcon, uNoticeBar, uModal, uButton } from '@/uni_modules/uview-ui'
import { billAlertList } from '@/api/bill'
import { mapState } from 'vuex'
	
	export default {
		components: { TaiCard, TaiLock, BatteryIcon },
		data() {
			return {
				roomCount: 0,
				loackName: '',
				lockData: 'vLczzp5tbrC7EifSo+5GJIYrbjLredI7P4SKaS52EzfrudMhI3k87cURPEvgPuoAILoo+LhRnyiy5bcP6nVA44RsT3/YuciPdoVsbqWNm/ZOv0FmPivLvv49ReJaoKS22eTSuQpY0z60Jzq/Os3p84c/cQZuGOFT1wSHgv+EBlc3fADrkH888zuES3yhG93v51tNhXN+A7s7lvGCvkP6IQsZ+ThmsM3JlCCQ4aA6ctJ7p/ETs5XupxVCvBSYS/XjpXlX3kAvYTpLWcVEGEERZk7VNP0hGR0Ul9lSrow+S1tzi26etdijgxQW5oD51AlEO+KUNHcmrZHJTur/SulamX7oQvkPjZNfEP2XY47oHPvOXpipbeZBCIwfunB7uDwNIL8dCpbg2BbJgdDtSefq8lb5CtimlPaSIyPU4K/2BOxkmvEuK0MC8todl9VvaH/6p/H9znWQ2k41dOFu8gQYtiwV+W60VkVA22lBZb15Fko5iDyGQf3PQCGNB7liQpVyQ6mvK8j8w5H53WEhdLJIokx+9ucJOo9IuSufTFd+NabvNgS/FQbUZq/EQ3pj1bKkOi9YQhL5uu+67byIMTMRHlf7S0prs0207zglpOcMZtDbuReTdcZ7vqKfvVxpW59KCDtu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bN3EVjcy7gDu8WydUEX5ll51egkIMEH+Nj69MzZcr8DsqrGHwIq/nkoRJy4oAqxY9k7lg9Ij2gkrUnzWAVTN8BECQ8FWwn9zArAwLShvjAg07/YmwfTXecOVW3uSXLkAoLPQeScOY3rBwF2rHDiDYHUoBdEg7nJNAqsf/7CxyrXtuZ80Dlh9BywD22SxtP1bLvGTJVtPx+mf9Fc97SAHvfhhqtny8+3wRLspUtp+NfrUUeHj9NgzBMhROeoJV6TV2hi+moZkK1cgVm5SmNAkk5SLkF+zIHppJPh0pvlnU5amh6g0wZQxuBoZuwi6k9mtz+46elxB1zgaDO8LYVsTyGv5jzUebl0hS/0jlSAcLy+XEVoS1p5hYGx91jwsG2fiEzxr++t6gm1Zry2XccnAgbPul/JsQXK5+r3zYT+BxOvixq4v1BusnRKN/fmyJWtGZwiO54k1AzlMUK9YfdstrFEMEgGuU7K/BULBL7poBpOrY07XRvv+zNPxCShU+FLz6IGjZrC0xzOrisoNz949TUT7R3gMsEd6jJRpgEQPxABLc1QXxYjYQq+hBlecFsWdV9eoOdqtNBSxJdQJsLQs7xRsaBeMSK3+3nYz5Q70l/D4/8VhZ22nIi59JZ2APzWpBN9aJdwDtHBlES6bQTOwZ6MPOjFjoLvHNNFSfyk/25TiIk6EfuvFF5MZDaHLv2LhGYLI6eONT4Ejo1A9vjNt+5HOqtDAx6DzRCYPQvR6Wfu42lR8p/AlGxvtqIXb88WQ435hJ04rHKwJ3BoJylSW1NWqotVC89PJfAhxiqxkArLCAw==',
				list: [{
						image: banner01,
						title: '昨夜星辰昨夜风，画楼西畔桂堂东'
					},
					{
						image: banner02,
						title: '身无彩凤双飞翼，心有灵犀一点通'
					},
					{
						image: banner03,
						title: '谁念西风独自凉，萧萧黄叶闭疏窗，沉思往事立残阳'
					}
				],
				lockList: [],
				roomList: [],
				needRefresh: false,
				alertList: [],
				showModal: false,
				currentAlert: {},
				modalTitle: '通知详情',
				modalContent: '',
				overdueCount: 0,
				balanceCount: 0,
			}
		},
	computed: {
		...mapState({
			hasOverdueBill: state => state.user.hasOverdueBill
		}),
		noticeList() {
			if (this.alertList.length === 0) return [];
			let list = this.alertList.map((alert) => {
				let message = '';
				switch (alert.type) {
					case 1: // 房租预警
						message = `${alert.roomDetail.buildingName || ''} ${alert.roomDetail.name || ''}房租即将到期，请及时缴纳！`;
						break;
					case 2: // 房租欠费
						message = `${alert.roomDetail.buildingName || ''} ${alert.roomDetail.name || ''}房租已逾期，请尽快缴纳！`;
						break;
					case 3: // 电费余额不足
						message = `${alert.roomDetail.buildingName || ''} ${alert.roomDetail.name || ''}电费余额不足，请及时充值！`;
						break;
					default:
						message = '您有一条新的通知，请查看！';
				}
				return message;
			})
			console.log(list);
			
			return list;
		}
		},
		methods: {
			unBindWechat() {
				unbindWechat()
			},
			// 跳转门锁设置
			toSettingLock(row) {
				this.$tab.navigateTo(`/pages/home/lock-setting/index?lockId=${row.lockId}&lockData=${row.lockData}`)
			},
			// 跳转用电记录
			toElectricityRecord(item) {
				this.$tab.navigateTo(`/pages/home/electricify-record/index?roomId=${item.roomId}`)
			},
			// 点击事件
			toClickItem(item) {
				console.log("点hi了");
				
				// 如果有逾期账单且是门锁或门禁，则禁止操作
				if (this.hasOverdueBill && (item.deviceType === 1 || item.deviceType === 3)) {
					uni.showToast({
						title: '您有逾期账单，请先缴纳后再使用门禁功能',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				if (item.deviceType === 1) {
					// 门锁
					this.toSettingLock(item)
				} else if (item.deviceType === 2) {
					// 电表
					this.toElectricityRecord(item)
				} else if (item.deviceType === 3) {
					// 门禁
					this.unLock(item)
				}
			},
			/* 获取预警或逾期账单列表 */
			getBillAlertList(type) {
				billAlertList(type).then(res => {
					if (res.data && res.data.length > 0) {
						this.overdueCount = this.overdueCount + res.data.length;
						let list = res.data.map((item) => {
							return {
								...item,
								type: type
							}
						})
						this.alertList = [...this.alertList, ...list];
						this.showNoticeDetail(0);
					}
				})
			},
			/* 获取余额不足的电表列表 */
			getLowBalanceMeters() {
				lowBalanceMeters().then(res => {
					if (res.data && res.data.length > 0) {
						// 为电表数据添加type=3标识
						const formattedData = res.data.map(item => ({
							...item,
							type: 3 // 电费余额不足类型
						}));
						this.alertList = [...this.alertList, ...formattedData];
					}
				})
			},
			/* 显示通知详情 */
			showNoticeDetail(index) {
				if (this.alertList.length === 0) return;
				this.currentAlert = this.alertList[index];
				this.showModal = true;
			},
			/* 关闭弹窗 */
			closeModal() {
				this.showModal = false;
			},
			/* 获取预警类型名称 */
			getAlertTypeName(type) {
				switch (type) {
					case 1:
						return '房租预警';
					case 2:
						return '房租欠费';
					case 3:
						return '电费余额不足';
					default:
						return '未知类型';
				}
			},
			/* 去缴费/充值 */
			goToPay() {
				const alert = this.currentAlert;
				if (alert.type === 3) {
					// 电费充值
					this.$tab.navigateTo(`/pages/home/recharge/index?roomId=${alert.roomId}&name=${alert.roomName || ''}&remainAmount=${alert.money || 0}`);
				} else {
					// 房租缴费
					this.$tab.navigateTo(`/pages/billing/index?roomId=${alert.roomId}`);
				}
				this.closeModal();
			},
			async unLock(item) {
				// 如果有逾期账单且是门锁或门禁，则禁止操作
				if (this.hasOverdueBill && (item.deviceType === 1 || item.deviceType === 3)) {
					uni.showToast({
						title: '您有逾期账单，请先缴纳后再使用门禁功能',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				uni.showLoading();
				try{
					switch (item.deviceType) {
						case 1:
							requirePlugin("myPlugin", ({ controlLock }) => {
								// 蓝牙开锁
								controlLock({controlAction: 3, lockData: item.lockData }).then(res => {
									console.log(res);
									uni.hideLoading();
									uni.showToast({title: res.errorMsg, icon: 'none'});
									if (res.errorCode == 0) {
										// 此处可以更新电量信息
										console.log("电量：>>>", res.electricQuantity);
									}
								});
							});
							break;
						case 3:
							await faceLockUnLock(item.faceLockId);
							uni.showToast({
								title: "开锁成功",
								icon: 'success'
							})
							break;
						default:
							break;
					}
				}catch(e){
					console.log(e);
					uni.showToast({title: "解锁失败，请联系管理员", icon: 'error'});
				}
				
			},
			/* 获取关联门锁列表 */
			getAssociatedDevice() {
				associatedDevice().then(res => {
					console.log(res.data);
					let resData = res.data;
					this.lockList = resData.map(item => {
						if (item.lockInfo) {
							item.lockInfo = JSON.parse(item.lockInfo);
						}
						switch (item.deviceType) {
							case 1: // 门锁
								item.deviceName = item.lockName;
								break;
							case 2: // 电表
								item.deviceName = item.name;
								break;
							case 3: // 门禁
								item.deviceName = item.faceLockName;
								break;
							default:
								break;
						}
						return item;
					});
				})
			},
			/* 获取绑定的房间列表 */
			getRoomList() {
				roomList().then(res => {
					this.roomList = res.data;
					this.roomCount = res.data.length;
				});
			},
			/* 点击账单 */
			goBill() {
				if (this.roomCount > 1) {
					this.$tab.navigateTo('/pages/billing/roomList')
				} else {
					if (this.roomList.length > 0) {
						this.$tab.navigateTo('/pages/billing/index?roomId=' + this.roomList[0].roomId)
					} else {
						uni.showToast({
							title: '暂无房间，请先绑定房间',
							icon: 'none'
						})
					}
				}
			},
			/* 去充值 */
			toRecharge(item) {
				uni.navigateTo(`/pages/home/recharge/index?roomId=${item.roomId}&name=${item.name}&remainAmount=${item.remainAmount}&electricityMeterId=${item.electricityMeterId}`)
			},
			goToRooms() {
				uni.navigateTo({
					url: '/pages/home/rooms/index'
				})
			}
		},
		onLoad: function() {
			this.getAssociatedDevice();
			this.getRoomList();
			this.alertList = [];
			this.overdueCount = 0
			this.getBillAlertList(1);
			this.getBillAlertList(2);
			this.getLowBalanceMeters();
			
			uni.$on('refreshDeviceInfo', () => {
				this.getAssociatedDevice();
			});
		},
		onPullDownRefresh() {
			console.log("ddd")
			this.getAssociatedDevice();
			this.getRoomList();
			this.alertList = [];
			this.overdueCount = 0
			this.getBillAlertList(1);
			this.getBillAlertList(2);
			this.getLowBalanceMeters();
		},
		onShow: function() {
			if (this.needRefresh) {
				this.getAssociatedDevice();
				this.needRefresh = false;
			}
		},
		onUnload: function() {
			uni.$off('refreshDeviceInfo');
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		// align-items: center;
		justify-content: center;
		padding: 32rpx 32rpx;
	}
	.flex-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.tips {
		margin-bottom: 12rpx;
		text-align: left;
		font-size: 32rpx;
	}

	.operation-bar {
		display: flex;
		align-items: center;
		margin-top: 24rpx;
	}

	.operation-item {
		position: relative;
		width: calc((100% - 36rpx) / 4);
		margin-right: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		background-color: #fff;
		border-radius: 5px;

		&:last-child {
			margin-right: 0rpx;
		}

		.icon-box {
			height: 50rpx;
			width: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
			margin-right: 12rpx;
			background-color: aliceblue;
		}

		/deep/ .text-badge {
			.u-badge {
				font-size: 12rpx !important;
				line-height: 16rpx !important;
				top: -6rpx !important;
			}
		}
	}
	.lock-section {
		margin-top: 24rpx;
	}
	.empty-lock {
		width: 100%;
		padding: 20px 0;
		text-align: center;
	}
	.lock-bar {
		display: flex;
		flex-wrap: wrap;
	}
	.lock-item {
		width: calc(50% - 12rpx);
		margin-right: 22rpx;
		margin-bottom: 24rpx;
		&:nth-of-type(2n) {
			margin-right: unset;
		}
	}
	
	.lock-item-disabled {
		position: relative;
		opacity: 0.7;
		
		&::after {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.1);
			z-index: 1;
			border-radius: 8rpx;
		}
	}
	
	.pre-dot {
		position: relative;
		font-size: 24rpx;
		color: var(--tai-tips-color);
		// color: $u-tips-color;
		&:before {
			content: '';
			position: absolute;
			width: 10rpx;
			height: 10rpx;
			border-radius: 50%;
			background-color: var(--tai-type-warning);
			left: -20rpx;
			top: 50%;
			transform: translateY(-50%);
		}
	}
	
	.disabled-text {
		color: #999 !important;
		
		&:before {
			background-color: #999;
		}
	}
	
	.overdue-badge {
		position: absolute;
		top: -20rpx;
		right: -20rpx;
		background-color: #fa3534;
		color: #fff;
		font-size: 16rpx;
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		white-space: nowrap;
	}

	.notice-bar {
		margin-top: 24rpx;
		border-radius: 24rpx;
		overflow: hidden;
	}
	
	.empty-notice {
		padding: 0 24rpx;
		height: 48rpx;
		line-height: 48rpx;
		font-size: 24rpx;
		color: #fa3534;
		background-color: #fdf6ec;
		border-radius: 24rpx;
		text-align: center;
	}
	
	.modal-content {
		padding: 20rpx;
	}
	
	.modal-item {
		display: flex;
		margin-bottom: 16rpx;
		font-size: 28rpx;
	}
	
	.modal-label {
		color: #666;
		width: 160rpx;
	}
	
	.modal-value {
		color: #333;
		flex: 1;
	}
	
	.modal-action {
		margin-top: 30rpx;
		display: flex;
		justify-content: center;
	}
</style>
